package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.JsonResult;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    @RequiresPermissions(value = {"role:list", "角色查询"},logical = Logical.OR)
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo")QueryObject qo){
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("result",pageInfo);
        return "/role/list";
    }

    @RequiresPermissions(value = {"role:input", "角色编辑页面"},logical = Logical.OR)
    @RequestMapping("/input")
    public String input(Long id,Model model){
        List<Permission> permissions = permissionService.selectAll();
        model.addAttribute("permissions",permissions);
        if (id != null) {
            Role role = roleService.selectByPrimaryKey(id);
            model.addAttribute("role",role);
        }

        return "/role/input";
    }

    @RequiresPermissions(value = {"role:saveOrUpdate", "角色/新增保存"},logical = Logical.OR)
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids){

        if (role.getId() != null) {
            roleService.updateByPrimaryKey(role,ids);
        }else{
            roleService.insert(role,ids);
        }
        return "redirect:/role/list.do";
    }

    @RequiresPermissions(value = {"role:delete", "角色删除"},logical = Logical.OR)
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        roleService.deleteByPrimaryKey(id);
        return new JsonResult();
    }
}
